import { _decorator, Component, Node } from 'cc';
import { BaseTs } from '../../Prefabs/Scripts/BaseTs';
const { ccclass, property } = _decorator;

@ccclass('EventUtil')
export class EventUtil extends BaseTs {

    /**
     * 事件监听的Map
     */
    private eventMap: any = {}

    public static INSTANCE: EventUtil = null;

    protected onLoad(): void {
        if (EventUtil.INSTANCE == null) {
            EventUtil.INSTANCE = this
        }
    }

    /**
     * 添加一个事件监听
     * @param eventName 事件名称
     * @param callback 回调方法
     * @param target  目标对象
     */
    public addEventListen(eventName: string, callback: any, target: any) {

        
        

        var eventEntity = this.eventMap[eventName];
        if (eventEntity) {
            this.removeEventListen(eventName)
        }

        // 组装对象信息
        var eventData = {
            eventName: eventName,
            callback: callback,
            target: target
        }
        this.eventMap[eventName] = eventData
    }

    /**
     * 删除指定的事件
     * @param eventName 需要删除的事件名称
     */
    public removeEventListen(eventName: string) {
        this.eventMap[eventName] = null
    }


    /**
     * 执行某个事件
     * @param eventName 事件名称
     * @param data 传递的参数
     */
    public invoke(eventName: string, data: any) {

        var eventEntity = this.eventMap[eventName];
        
        console.log('eventEntity' , eventEntity) 
        if (eventEntity) {
            eventEntity.callback.call(eventEntity.target, data)
        }
    }
}

